import { RouteRecordRaw } from "vue-router";
import { constantRoutes, roleRoutes } from "@/router";
import { store } from "@/store";
import MenuAPI, { RouteVO } from "@/api/menu";

export const usePermissionStore = defineStore("permission", () => {
  /** 所有路由，包括静态和动态路由 */
  const routes = ref<RouteRecordRaw[]>([]);
  /** 混合模式左侧菜单 */
  const mixLeftMenus = ref<RouteRecordRaw[]>([]);

  /**
   * 生成动态路由
   */
  function generateRoutes(perms: any[]) {
    return new Promise<RouteRecordRaw[]>((resolve, reject) => {
      const dynamicRoutes = transformRoutes(perms, roleRoutes);
      routes.value = constantRoutes.concat(dynamicRoutes);
      resolve(dynamicRoutes);
    });
  }

  /**
   * 混合模式菜单下根据顶部菜单路径设置左侧菜单
   *
   * @param topMenuPath - 顶部菜单路径
   */
  const setMixLeftMenus = (topMenuPath: string) => {
    const matchedItem = routes.value.find((item) => item.path === topMenuPath);
    if (matchedItem && matchedItem.children) {
      mixLeftMenus.value = matchedItem.children;
    }
  };

  return {
    routes,
    generateRoutes,
    mixLeftMenus,
    setMixLeftMenus,
  };
});

/**
 * 转换路由数据为组件
 */
const transformRoutes = (perms: string[], roleRoutes: any[]) => {
  const asyncRoutes: any[] = [];
  roleRoutes.forEach((route) => {
    const tmpRoute = { ...route };

    if (tmpRoute.perm && tmpRoute.children && tmpRoute.children.length) {
      tmpRoute.children = transformRoutes(perms, route.children);
      if (!tmpRoute.children || !tmpRoute.children.length) {
        return []
      }
    } else if (tmpRoute.perm && !perms.includes(tmpRoute.perm) && !perms.includes('*')) {
      return [];
    }
    asyncRoutes.push(tmpRoute);
  });

  return asyncRoutes;
};

/**
 * 在组件外使用 Pinia store 实例
 * @see https://pinia.vuejs.org/core-concepts/outside-component-usage.html
 */
export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
